import { MdSnackBar } from '@angular/material';
import { MessageBoxService, GrowlMessageType } from './../messageBoxService';
import { CacheManager } from './../../common/cacheManager';
import { SyncDataUrl } from './../../model/clerkDataContext';
import { StoreService } from './../../service/store.service';
import { ModifierService } from './../../service/modifier.service';
import { InventoryService } from './../../service/inventory.service';
import { NavigateService } from './../../service/navigate.service';
import { SyncDataService } from './../../service/sync.service';
import { Component, OnInit, Output, EventEmitter } from '@angular/core';

export class DataSyncService {
    private dataSync: DataSync;
    static Current: DataSyncService = new DataSyncService();

    Regist(dataSync: DataSync) {
        this.dataSync = dataSync;
    }

    async show() {
        if (this.dataSync) {
            this.dataSync.sync = true;
            await this.dataSync.syncData();
        }
    }
}

@Component({
    selector: "data-sync",
    template: `
        <div fxLayout="column" class="fullscreen bgcolor-white" *ngIf="sync">
            <md-toolbar class="bgcolor-primary">
                <header fxLayout="row" fxLayoutAlign="center center" class="pct100">
                    <span fxFlex="100%" class="color-white">数据同步</span>
                    <!--<div class="layout layout-align-center-center padding-lr-10">
                        <span>跳过同步</span>
                        <span class="icon-forward-right-circle"></span>
                    </div>-->
                    <span class="i-refresh fa-lg noshrink" (click)="reSyncdata()"></span>
                </header>
            </md-toolbar>
            <div fxFlex="100%" fxLayout="column" fxLayoutAlign="center center">
                <div class="padding-5 text-center">
                    正在同步
                </div>
                <div fxLayout="column" fxLayoutAlign="center center" class="sync-progress-container">
                    <md-progress-spinner class="sync-progress" mode="determinate" [value]="progressValue"></md-progress-spinner>
                    <div class="sync-progress-percent pct100 text-center">{{progressValue.toFixed(0)}}%</div>
                </div>
            </div>
            <footer class="sync-footer"></footer>
        </div>
    `,
    styleUrls: ['./dataSync.component.scss']
})

export class DataSync {
    constructor(
        private syncSvr: SyncDataService,
        private router: NavigateService,
        private invtSvr: InventoryService,
        private modSvr: ModifierService,
        private storeSvr: StoreService,
        private snackBar: MdSnackBar,
        private msgSvr: MessageBoxService
    ) {
        DataSyncService.Current.Regist(this);
    }

    @Output() syncSuccess: EventEmitter<any> = new EventEmitter<any>();

    sync: boolean = false;
    public data;
    progressValue: number = 0;
    private syncDataUrls: SyncDataUrl[];

    /**
     * 同步完成缓存必要的数据
     */
    async syncCompleted() {
        try {
            CacheManager.Current.clear();
            let invtList = await this.invtSvr.GetInventory();
            let store = await this.storeSvr.getStoreInfo();
            CacheManager.Current.add({ key: "invtList", value: invtList });
            this.storeSvr.CurrentStore = store;
            this.sync = false;
            this.syncSuccess.emit(null);
        } catch (error) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, error);
        }
    }

    async syncData() {
        try {
            //清空indexedDB
            await this.syncSvr.ClearAll();
            this.syncDataUrls = await this.syncSvr.syncResources();
            if (this.syncDataUrls && this.syncDataUrls.length) {
                this.syncDataUrls.forEach(item => {
                    this.syncSvr.SaveSynchroData(item);
                });
            } else {
                this.sync = false;
                this.syncSuccess.emit(null);
                return;
            }
            (function (that) {
                let tick = setInterval(function () {
                    let num = 0;
                    that.syncDataUrls.forEach(element => {
                        if (element.complete) {
                            num += 1;
                        }
                    });
                    that.progressValue = num / that.syncDataUrls.length * 100;
                    if (that.progressValue >= 100) {
                        that.progressValue = 100;
                        that.syncCompleted();
                        clearInterval(tick);
                    }
                }, 100);
            })(this);
        } catch (error) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, error);
        }
    }

    /**
     * 重新进行同步
     */
    async reSyncdata() {
        await this.syncData();
    }
}